package com.learn.security.service.impl;

import com.learn.security.bo.AccessToken;
import com.learn.security.bo.ApiResult;
import com.learn.security.cache.Cache;
import com.learn.security.constant.CacheName;
import com.learn.security.provider.JwtProvider;
import com.learn.security.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @author : Yu.Tan
 * @date : 2023/6/27 17:03
 * @desc : **
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtProvider jwtProvider;
    @Autowired
    private Cache caffeineCache;

    @Override
    public ApiResult login(String loginAccount, String password) {
        log.debug("进入login方法");
        // 1 创建UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginAccount, password);
        // 2 认证
        Authentication authenticate = this.authenticationManager.authenticate(authenticationToken);
        // 3 保存认证信息
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        // 4 生成自定义token
        UserDetails userDetails = (UserDetails) authenticate.getPrincipal();
        AccessToken token = jwtProvider.createToken(userDetails);
        // 放入缓存
        caffeineCache.put(CacheName.USER, userDetails.getUsername(), userDetails);
        return ApiResult.ok(token);
    }
}
